package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;



    @PostMapping
    public R save(@RequestBody DishDto dishDto){
        //先存储dish数据
        dishService.save(dishDto);
        //再存储dishFlavor数据
        //因为口味表是没有dishId，所以要遍历这个集合一个个设置进去
        List<DishFlavor> flavors = dishDto.getFlavors();

        if(flavors!=null&&flavors.size()>0){

            Long id = dishDto.getId();
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(id);
                //设置完dishId就是完整的数据，插入到口味表中
                dishFlavorService.save(flavor);
            }
        }
        return R.success("添加成功！");
    }

    /**
     * 分页查询菜品数据
     */

    @GetMapping("/page")
    public R page(int page,int pageSize,String name){
        //创建分页构造器
        Page pageInfo= new Page(page,pageSize);
        //创建条件构造器
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        qw.orderByAsc(Dish::getUpdateTime);
        //进行查询
        pageInfo = dishService.page(pageInfo, qw);
       // return pageInfo!=null?R.success(pageInfo):R.error("查询失败");

        //这里不能直接返回小宋
        //因为查询出来的菜品是显示的为categoryid，不是分类的名字
        //要根据categoryId来获取种类名称
        long total = pageInfo.getTotal();
        List<Dish> records = pageInfo.getRecords();
        //创建集合存放dishdto数据
        ArrayList<DishDto> dishDtos = new ArrayList<>();
        for (Dish dish : records) {
            Long categoryId = dish.getCategoryId();
            //根据categoryId来获取种类名称
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            //到这里就有了全部返回的数据
            //不能返回dish，dish没有categoryName属性，要返回Dishdto
            //把这里的数据都给dishdto
            DishDto dishDto = new DishDto();
            dishDto.setCategoryName(categoryName);
            //把dish的数据复制进去
            BeanUtils.copyProperties(dish,dishDto);
            dishDtos.add(dishDto);
        }

        HashMap map = new HashMap();
        map.put("total",total);
        map.put("records",dishDtos);
        return R.success(map);
    }

    /**
     * 修改菜品数据
     * 先回显数据
     */
    @GetMapping("/{id}")
    public R update(@PathVariable Long id){
        //先查询到dish
        Dish dish = dishService.getById(id);
        //因为dishId=dishFlavorDishId
        //再查询到dishFlavor数据
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId,id);
        List<DishFlavor> list = dishFlavorService.list(qw);
        //要回显dishdto
        DishDto dishDto = new DishDto();
        //添加dish
        BeanUtils.copyProperties(dish,dishDto);
        //添加dishFlavor
        dishDto.setFlavors(list);
        return R.success(dishDto);
    }

    /**
     * 修改菜品数据
     * @param dishDto
     * @return
     */
    @PutMapping
    public R update(@RequestBody DishDto dishDto){
        //先修改dish
        dishService.updateById(dishDto);
        //再修改dishFlavor
        //先删除dishFlavor数据
        Long id = dishDto.getId();
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId,id);
        dishFlavorService.remove(qw);
        //再进行添加口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            dishFlavorService.save(flavor);
        }
        return R.success("修改成功！");
    }

    /**
     * 删除菜品
     */
//    @DeleteMapping
//    public  R delete(List<Long> ids){
//        log.info("ids:{}",ids);
    //业务操作
//        return null;
//    }

    /**
     * 起售、停售、
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R update(@PathVariable Integer status, @RequestParam List<Long> ids){
        LambdaUpdateWrapper<Dish> qw = new LambdaUpdateWrapper<>();
        qw.set(Dish::getStatus,status);
        qw.in(Dish::getId,ids);
        dishService.update(qw);
        // update dish set status = ? where id = ?
        for (Long id : ids) {
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(status);
            dishService.updateById(dish);
        }
        return R.success("修改成功！");

    }

    /**
     * 新增套餐
     * 根据分类id查询分类下的所有菜品集合
     */

    @GetMapping("/list")
    public R<List<DishDto>> select(Dish dish){
//        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
//        qw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
//        qw.eq(Dish::getStatus,1);
//        qw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        List<Dish> list = dishService.list(qw);
//        return R.success(list);
        //前台登录之后改造
        //不但要查询菜品
        //还要查询菜品的口味数据
        Long categoryId = dish.getCategoryId();
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(Dish::getCategoryId,categoryId);
        qw.eq(Dish::getStatus,1);
        qw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishes = dishService.list(qw);
        //创建DishDto集合
        ArrayList<DishDto> dishDtos = new ArrayList<>();

        for (Dish dish1 : dishes) {
            //查询口味数据
            Long dishId = dish1.getId();
            LambdaQueryWrapper<DishFlavor> qw2 = new LambdaQueryWrapper<>();
            qw2.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavors = dishFlavorService.list(qw2);
            DishDto dishDto = new DishDto();
            //把菜品数据复制进去
            BeanUtils.copyProperties(dish1,dishDto);
            dishDto.setFlavors(dishFlavors);
            dishDtos.add(dishDto);
        }
        return  dishDtos!=null?R.success(dishDtos):R.error(null);

    }



}
